package entry

import (
	"com.lh.basic.service/lib/middleware"
	"com.lh.basic.service/lib/tools"
	"com.lh.basic.service/pb/auth"
	"com.lh.basic.service/pb/menu"
	au "com.lh.basic.service/service/auth"
	me "com.lh.basic.service/service/menu"
	"com.lh.user.service/pb/user"
	"fmt"
	"github.com/improbable-eng/grpc-web/go/grpcweb"
	"google.golang.org/grpc"
	"log"
	"net"
	"net/http"
	"sync"
)

func InitGrpcWeb(opts *user.ServeConfig, wg *sync.WaitGroup) {
	defer wg.Done()
	grpcServer := grpc.NewServer(grpc.UnaryInterceptor(tools.AuthFilterInterceptor))
	auth.RegisterAuthServiceServer(grpcServer, &au.Auth{})
	menu.RegisterMenuServiceServer(grpcServer, &me.Menu{})
	web := grpcweb.WrapServer(grpcServer,
		grpcweb.WithOriginFunc(func(origin string) bool {
			// 允许所有来源，生产环境应限制
			return true
		}),
		grpcweb.WithWebsockets(true),
		grpcweb.WithWebsocketOriginFunc(func(req *http.Request) bool {
			// 允许所有来源，生产环境应限制
			return true
		}),
		grpcweb.WithAllowedRequestHeaders([]string{"Sid", "Uuid", "Token"}),
	)

	app := &http.Server{
		Handler: middleware.GrpcWebCors(web, "*"),
	}
	serve, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port-1000))
	if err != nil {
		log.Printf("failed to listen: %v", err)
	}
	log.Printf("gRPC-Web proxy started on: %v", serve.Addr())
	if err := app.Serve(serve); err != nil {
		log.Printf("failed to serve: %v", err)
	}
}
